package com.qianbao.qianbaobusiness.ui.cashier.databill;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qianbao.qianbaobusiness.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 自定义的布局，用来管理三个子控件，其中一个是下拉头，一个是包含内容的pullableView（可以是实现Pullable接口的的任何View），
 * 还有一个上拉头，更多详解见博客http://blog.csdn.net/zhongkejingwang/article/details/38868463
 */
public class PullToRefreshLayout extends RelativeLayout {
    public static final String TAG = "PullToRefreshLayout";
    // 初始状态
    public static final int INIT = 0;
    // 释放刷新
    public static final int RELEASE_TO_REFRESH = 1;
    // 正在刷新
    public static final int REFRESHING = 2;
    // 释放加载
    public static final int RELEASE_TO_LOAD = 3;
    // 正在加载
    public static final int LOADING = 4;
    // 刷新操作完毕
    public static final int REFRESH_DONE = 5;
    // 加载更多操作完毕
    public static final int LOADMORE_DONE = 6;

    public static final int DONE = 7;

    public static final int NONE = 0;
    // 刷新成功
    public static final int SUCCEED = 0;
    // 刷新失败
    public static final int FAIL = 1;
    // 没有新数据
    public static final int NO_DATA = 2;
    // 下拉的距离。注意：pullDownY和pullUpY不可能同时不为0
    public float pullDownY = 0;
    // 回滚速度
    public float MOVE_SPEED = 8;
    // 当前状态
    private int state = INIT;
    // 刷新回调接口
    private OnRefreshListener mListener;
    private OnRegressionListener mRegressionListener;
    // 按下Y坐标，上一个事件点Y坐标
    private float downY, lastY;
    // 上拉的距离
    private float pullUpY = 0;
    // 释放刷新的距离
    private float refreshDist = 200;
    // 释放加载的距离
    private float loadmoreDist = 200;
    private MyTimer myTimer;
    // 第一次执行布局
    private boolean isLayout = false;
    // 在刷新过程中滑动操作
    private boolean isTouch = false;
    // 手指滑动距离与下拉头的滑动距离比，中间会随正切函数变化
    private float radio = (float) 1.2;
    // 自动回滚刷新界面的时间
    private int refreshTime = 5;

    // 下拉箭头的转180°动画
    private RotateAnimation rotateAnimation;
    // 均匀旋转动画
    private RotateAnimation refreshingAnimation;

    // 下拉头
    private View refreshView;
    // 下拉的箭头
    private View pullView;
    // 正在刷新的图标
    private View refreshingView;
    // 刷新结果图标
    //	private View refreshStateImageView;
    // 刷新结果：成功或失败
    private TextView refreshStateTextView;
    // 刷新时间
    private TextView tv_time;

    // 上拉头
    private View loadmoreView;
    // 上拉的箭头
    private View pullUpView;
    // 正在加载的图标
    private View loadingView;
    // 加载结果图标
    private View loadStateImageView;
    // 加载结果：成功或失败
    private TextView loadStateTextView;

    private boolean pullDownEnabled = true;
    private boolean pullUpEnabled = true;

    private AnimationDrawable animaion;
    /**
     * 执行自动回滚的handler
     */
    Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (myTimer == null) {
                return;
            }
            // 回弹速度随下拉距离moveDeltaY增大而增大
            MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
                    / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
            if (!isTouch) {
                // 正在刷新，且没有往上推的话则悬停，显示"正在刷新..."
                if (state == REFRESHING && pullDownY <= refreshDist) {
                    pullDownY = refreshDist;
                    myTimer.cancel();
                } else if (state == LOADING && -pullUpY <= loadmoreDist) {
                    pullUpY = -loadmoreDist;
                    myTimer.cancel();
                }

            }
            if (pullDownY > 0)
                pullDownY -= MOVE_SPEED;
            else if (pullUpY < 0)
                pullUpY += MOVE_SPEED;
            if (pullDownY < 0) {
                // 已完成回弹
                pullDownY = 0;
                pullView.clearAnimation();
                // 隐藏下拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
                if (state != REFRESHING && state != LOADING)
                    changeState(INIT);
                myTimer.cancel();
                requestLayout();
            }
            if (pullUpY > 0) {
                // 已完成回弹
                pullUpY = 0;
                pullUpView.clearAnimation();
                // 隐藏上拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
                if (state != REFRESHING && state != LOADING)
                    changeState(INIT);
                myTimer.cancel();
                requestLayout();
            }
            Log.d("handle", "handle");
            // 刷新布局,会自动调用onLayout
            requestLayout();
            // 没有拖拉或者回弹完成
            if (pullDownY + Math.abs(pullUpY) == 0)
                myTimer.cancel();
        }
    };
    // 实现了Pullable接口的View
    private View pullableView;
    // 过滤多点触碰
    private int mEvents;
    // 这两个变量用来控制pull的方向，如果不加控制，当情况满足可上拉又可下拉时没法下拉
    private boolean canPullDown = true;
    private boolean canPullUp = true;
    private Context mContext;
    private int showSuccessStateTime = 200;

    public PullToRefreshLayout(Context context) {
        super(context);
        initView(context);
    }

    public PullToRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public void setOnRefreshListener(OnRefreshListener listener) {
        mListener = listener;
    }

    public void setOnRegressionListener(OnRegressionListener listener) {
        mRegressionListener = listener;
    }

    private void initView(Context context) {
        mContext = context;
        myTimer = new MyTimer(updateHandler);
        rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
                context, R.anim.reverse_anim);
        refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
                context, R.anim.rotating);
        // 添加匀速转动动画
        LinearInterpolator lir = new LinearInterpolator();
        rotateAnimation.setInterpolator(lir);
        refreshingAnimation.setInterpolator(lir);
    }

    private void hide() {
        if (myTimer != null) {
            myTimer.schedule(5);
        }
    }

    /**
     * 完成刷新操作，显示刷新结果。注意：刷新完成后一定要调用这个方法
     */
    /**
     * @param refreshResult PullToRefreshLayout.SUCCEED代表成功，PullToRefreshLayout.FAIL代表失败
     */
    public void refreshFinish(int refreshResult) {
        //修复refreshView为空时的空指针异常 2018/02/11
        if (refreshView != null) {
            refreshingView.clearAnimation();
            refreshingView.setVisibility(View.GONE);
        }
        switch (refreshResult) {
            case SUCCEED:
                // 刷新成功
                //添加pullView的空指针异常
                if (pullView != null) {
                    pullView.setVisibility(View.VISIBLE);
                    //			refreshStateImageView.setVisibility(View.VISIBLE);
                    pullView.setBackgroundResource(R.mipmap.icon_pulldown);
                }
                if (refreshStateTextView != null) {
                    refreshStateTextView.setText("刷新失败");
                }
                break;
            case FAIL:
            default:
                // 刷新失败
                //添加pullView的空指针异常
                if (pullView != null) {
                    pullView.setVisibility(View.VISIBLE);
                    //			refreshStateImageView.setVisibility(View.VISIBLE);
                    pullView.setBackgroundResource(R.mipmap.icon_pulldown);
                }
                if (refreshStateTextView != null) {
                    refreshStateTextView.setText("刷新失败");
                }
                break;
        }
        if (pullDownY > 0) {
            // 刷新结果停留1秒
            new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    changeState(DONE, REFRESH_DONE);
                    hide();
                }
            }.sendEmptyMessageDelayed(0, showSuccessStateTime);
        } else {
            changeState(DONE, REFRESH_DONE);
            hide();
        }
    }

    /**
     * 加载完毕，显示加载结果。注意：加载完成后一定要调用这个方法
     *
     * @param refreshResult PullToRefreshLayout.SUCCEED代表成功，PullToRefreshLayout.FAIL代表失败
     */
    public void loadmoreFinish(int refreshResult) {
        loadingView.clearAnimation();
        loadingView.setVisibility(View.GONE);
        switch (refreshResult) {
            case SUCCEED:
                // 加载成功
                loadStateImageView.setVisibility(View.VISIBLE);
                loadStateTextView.setText("加载成功");
                //loadStateImageView.setBackgroundResource(R.mipmap.load_succeed);
                break;
            case NO_DATA:
                loadStateImageView.setVisibility(View.VISIBLE);
                loadStateTextView.setText("已经到底了");
                //loadStateImageView.setBackgroundResource(R.mipmap.load_failed);
                break;
            case FAIL:
            default:
                // 加载失败
                loadStateImageView.setVisibility(View.VISIBLE);
                loadStateTextView.setText("加载失败");
                //loadStateImageView.setBackgroundResource(R.mipmap.load_failed);
                break;
        }
        if (pullUpY < 0) {
            // 刷新结果停留1秒
            new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    changeState(DONE, LOADMORE_DONE);
                    hide();
                }
            }.sendEmptyMessageDelayed(0, showSuccessStateTime);
        } else {
            changeState(DONE, LOADMORE_DONE);
            hide();
        }
    }

    private void changeState(int to) {
        changeState(to, NONE);
    }

    private void changeState(int to, int model) {
        state = to;
        switch (state) {
            case INIT:
                // 下拉布局初始状态
                //			refreshStateImageView.setVisibility(View.GONE);
                refreshStateTextView.setText("下拉可以刷新");
                pullView.clearAnimation();
                pullView.setVisibility(View.VISIBLE);
                pullView.setBackgroundResource(R.mipmap.icon_pulldown);
                // 上拉布局初始状态
                loadStateImageView.setVisibility(View.GONE);
                loadStateTextView.setText("上拉加载更多");
                pullUpView.clearAnimation();
                pullUpView.setVisibility(View.VISIBLE);
                break;
            case RELEASE_TO_REFRESH:
                // 释放刷新状态
                refreshingView.setVisibility(View.INVISIBLE);
                pullView.setVisibility(View.VISIBLE);
                refreshStateTextView.setText("松开后刷新");
                //			pullView.startAnimation(rotateAnimation);
                pullView.setBackgroundResource(R.mipmap.icon_pulldown);
                break;
            case REFRESHING:
                // 正在刷新状态
                pullView.clearAnimation();
                refreshingView.setVisibility(View.VISIBLE);
                pullView.setVisibility(View.INVISIBLE);
                //			refreshingView.startAnimation(refreshingAnimation);
                refreshStateTextView.setText("正在加载中");
                AnimationDrawable animationDrawable = (AnimationDrawable) refreshingView
                        .getBackground();
                animationDrawable.start();
                break;
            case RELEASE_TO_LOAD:
                // 释放加载状态
                loadStateTextView.setText("释放立即加载");
                //			pullUpView.startAnimation(rotateAnimation);
                break;
            case LOADING:
                // 正在加载状态
                //                pullUpView.clearAnimation();
                //                loadingView.setVisibility(View.VISIBLE);
                //                pullUpView.setVisibility(View.INVISIBLE);
                //                loadingView.startAnimation(refreshingAnimation);
                loadStateTextView.setText("载入中");
                break;
            case DONE:
                if (model == REFRESH_DONE) {
                    if (mRegressionListener != null) {
                        mRegressionListener.onRegression();
                    }
                } else if (model == LOADMORE_DONE) {

                }
                //                animaion.stop();
                break;
            default:
                break;
        }
    }

    /**
     * 不限制上拉或下拉
     */
    public void releasePull() {
        canPullDown = true;
        canPullUp = true;
    }

    public void lockPull() {
        canPullDown = false;
        canPullUp = false;
    }

    /*
     * （非 Javadoc）由父控件决定是否分发事件，防止事件冲突
     *
     * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                downY = ev.getY();
                lastY = downY;
                if (myTimer != null){
                    myTimer.cancel();
                }
                mEvents = 0;
                //			releasePull();
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                // 过滤多点触碰
                mEvents = -1;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mEvents == 0) {
                    if (pullDownEnabled && canPullDown && (pullDownY > 0 || (((Pullable)
                            pullableView).canPullDown() && state != LOADING))) {
                        // 可以下拉，正在加载时不能下拉
                        // 对实际滑动距离做缩小，造成用力拉的感觉
                        pullDownY = pullDownY + (ev.getY() - lastY) / radio;
                        if (pullDownY < 0) {
                            pullDownY = 0;
                            canPullDown = false;
                            canPullUp = true;
                        }
                        if (pullDownY > getMeasuredHeight())
                            pullDownY = getMeasuredHeight();
                        if (state == REFRESHING) {
                            // 正在刷新的时候触摸移动
                            isTouch = true;
                        }
                    } else if (pullUpEnabled && canPullUp && (pullUpY < 0 || (((Pullable)
                            pullableView).canPullUp() && state != REFRESHING))) {
                        // 可以上拉，正在刷新时不能上拉
                        pullUpY = pullUpY + (ev.getY() - lastY) / radio;
                        if (pullUpY > 0) {
                            pullUpY = 0;
                            canPullDown = true;
                            canPullUp = false;
                        }
                        if (pullUpY < -getMeasuredHeight())
                            pullUpY = -getMeasuredHeight();
                        if (state == LOADING) {
                            // 正在加载的时候触摸移动
                            isTouch = true;
                        }
                    } //else
                    //					releasePull();
                } else {
                    mEvents = 0;
                }
                lastY = ev.getY();
                // 根据下拉距离改变比例
                radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
                if (pullDownY > 0 || pullUpY < 0)
                    requestLayout();
                if (pullDownY > 0) {
                    if (pullDownY <= refreshDist && (state == RELEASE_TO_REFRESH || state == DONE)) {
                        // 如果下拉距离没达到刷新的距离且当前状态是释放刷新，改变状态为下拉刷新
                        changeState(INIT);
                    }
                    if (pullDownY >= refreshDist && state == INIT) {
                        // 如果下拉距离达到刷新的距离且当前状态是初始状态刷新，改变状态为释放刷新
                        changeState(RELEASE_TO_REFRESH);
                    }
                } else if (pullUpY < 0) {
                    // 下面是判断上拉加载的，同上，注意pullUpY是负值
                    if (-pullUpY <= loadmoreDist && (state == RELEASE_TO_LOAD || state == DONE)) {
                        changeState(INIT);
                    }
                    // 上拉操作
                    if (-pullUpY >= loadmoreDist && state == INIT) {
                        changeState(RELEASE_TO_LOAD);
                    }

                }
                // 因为刷新和加载操作不能同时进行，所以pullDownY和pullUpY不会同时不为0，因此这里用(pullDownY +
                // Math.abs(pullUpY))就可以不对当前状态作区分了
                if ((pullDownY + Math.abs(pullUpY)) > 8) {
                    // 防止下拉过程中误触发长按事件和点击事件
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (pullDownY > refreshDist || -pullUpY > loadmoreDist)
                // 正在刷新时往下拉（正在加载时往上拉），释放后下拉头（上拉头）不隐藏
                {
                    isTouch = false;
                }
                if (state == RELEASE_TO_REFRESH) {
                    changeState(REFRESHING);
                    // 刷新操作
                    if (mListener != null)
                        mListener.onRefresh(this);
                } else if (state == RELEASE_TO_LOAD) {
                    changeState(LOADING);
                    // 加载操作
                    if (mListener != null)
                        mListener.onLoadMore(this);
                } else if (state == LOADING || state == REFRESHING) {
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                }
                releasePull();
                hide();
            default:
                break;
        }
        // 事件分发交给父类
        super.dispatchTouchEvent(ev);
        return true;
    }

    /**
     * 自动刷新
     */
    public void autoRefresh() {
        AutoRefreshAndLoadTask task = new AutoRefreshAndLoadTask();
        task.execute(refreshTime);
    }

    /**
     * 自动加载
     */
    public void autoLoad() {
        pullUpY = -loadmoreDist;
        requestLayout();
        changeState(LOADING);
        // 加载操作
        if (mListener != null)
            mListener.onLoadMore(this);
    }

    private void initView() {
        if (refreshView == null) {
            layout();
        }
        // 初始化下拉布局
        pullView = refreshView.findViewById(R.id.pull_icon);
        refreshStateTextView = (TextView) refreshView.findViewById(R.id.state_tv);
        tv_time = (TextView) refreshView.findViewById(R.id.state_tv_time);
        refreshingView = refreshView.findViewById(R.id.refreshing_icon);
        //		refreshStateImageView = refreshView.findViewById(R.id.state_iv);
        // 初始化上拉布局
        pullUpView = loadmoreView.findViewById(R.id.pullup_icon);
        animaion = (AnimationDrawable) pullUpView.getBackground();
        animaion.start();
        loadStateTextView = (TextView) loadmoreView.findViewById(R.id.loadstate_tv);
        loadingView = loadmoreView.findViewById(R.id.loading_icon);
        loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("Test", "Test");
        layout();
    }

    private void layout() {
        if (!isLayout) {
            // 这里是第一次进来的时候做一些初始化
            refreshView = getChildAt(0);
            pullableView = getChildAt(1);
            loadmoreView = getChildAt(2);
            isLayout = true;
            initView();
            refreshDist = ((ViewGroup) refreshView).getChildAt(0).getMeasuredHeight();
            loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0).getMeasuredHeight();
        }
        // 改变子控件的布局，这里直接用(pullDownY + pullUpY)作为偏移量，这样就可以不对当前状态作区分
        refreshView.layout(0, (int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(), refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY));
        pullableView.layout(0, (int) (pullDownY + pullUpY), pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight());
        loadmoreView.layout(0, (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(), loadmoreView.getMeasuredWidth(),
                (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight() + loadmoreView.getMeasuredHeight());
    }

    public void setRefreshTime(String time) {
        //        refreshStateTextView.setText(time);
        if (tv_time == null) {
            initView();
        }
        tv_time.setText(time);
    }

    public void setCanPullDown(boolean canPullDown) {
        this.canPullDown = canPullDown;
    }

    public void setCanPullUp(boolean canPullUp) {
        this.canPullUp = canPullUp;
    }

    public void setPullDownEnabled(boolean pullDownEnabled) {
        this.pullDownEnabled = pullDownEnabled;
    }

    public void setPullUpEnabled(boolean pullUpEnabled) {
        this.pullUpEnabled = pullUpEnabled;
    }

    public void setPullEnabled(boolean enabled) {
        setPullDownEnabled(enabled);
        setPullUpEnabled(enabled);
    }

    /**
     * 刷新加载回调接口
     *
     * @author chenjing
     */
    public interface OnRefreshListener {
        /**
         * 刷新操作
         */
        void onRefresh(PullToRefreshLayout pullToRefreshLayout);

        /**
         * 加载操作
         */
        void onLoadMore(PullToRefreshLayout pullToRefreshLayout);
    }

    /**
     * 当刷新头回归为0的时候调用
     *
     * @author chenjing
     */
    public interface OnRegressionListener {
        void onRegression();
    }

    /**
     * @author chenjing 自动模拟手指滑动的task 一个异步任务的执行一般包括以下几个步骤：
     * 1.execute(Params...params)，执行一个异步任务，需要我们在代码中调用此方法，触发异步任务的执行。
     * 2.onPreExecute()，在execute(Params...params)被调用后立即执行，一般用来在执行后台任务前对UI做一些标记。
     * 3.doInBackground(Params...params)，在onPreExecute()完成后立即执行，用于执行较为费时的操作
     * ，此方法将接收输入参数和返回计算结果。 在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。
     * 4.onProgressUpdate(Progress...values)，在调用publishProgress(Progress...values)时，此方法被执行，直接将进度信息更新到UI组件上。
     * 5.onPostExecute(Result result)，当后台操作结束时，此方法将会被调用，计算结果将做为参数传递到此方法中，直接将结果显示到UI组件上。
     * 在使用的时候，有几点需要格外注意： 1.异步任务的实例必须在UI线程中创建。
     * 2.execute(Params...params)方法必须在UI线程中调用。
     * 3.不要手动调用onPreExecute()，doInBackground(Params...params)，onProgressUpdate(Progress... values)，onPostExecute(Result result)这几个方法。
     * 4.不能在doInBackground(Params... params)中更改UI组件的信息。
     * 5.一个任务实例只能执行一次，如果执行第二次将会抛出异常。
     */
    private class AutoRefreshAndLoadTask extends AsyncTask<Integer, Float, String> {

        @Override
        protected String doInBackground(Integer... params) {
            while (pullDownY < 4 / 3 * refreshDist) {
                pullDownY += MOVE_SPEED;
                publishProgress(pullDownY);
                try {
                    Thread.sleep(params[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            changeState(REFRESHING);
            // 刷新操作
            if (mListener != null)
                mListener.onRefresh(PullToRefreshLayout.this);
            hide();
        }

        @Override
        protected void onProgressUpdate(Float... values) {
            if (pullDownY > refreshDist)
                changeState(RELEASE_TO_REFRESH);
            // requestLayout：当view确定自身已经不再适合现有的区域时，该view本身调用这个方法要求parent
            // view重新调用他的onMeasure onLayout来对重新设置自己位置。
            // 特别的当view的layoutparameter发生改变，并且它的值还没能应用到view上，这时候适合调用这个方法。
            // invalidate：View本身调用迫使view重画。
            requestLayout();
        }

    }

    class MyTimer {
        private Handler handler;
        // 定时器
        private Timer timer;
        private MyTask mTask;

        public MyTimer(Handler handler) {
            this.handler = handler;
            timer = new Timer();
        }

        public void schedule(long period) {
            if (mTask != null) {
                mTask.cancel();
                mTask = null;
            }
            mTask = new MyTask(handler);
            // 大意是在延时delay毫秒后重复的执行task，周期是period毫秒
            timer.schedule(mTask, 0, period);
        }

        public void cancel() {
            if (mTask != null) {
                mTask.cancel();
                mTask = null;
            }
        }

        public void destoryCancel() {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (mTask != null) {
                mTask.cancel();
                mTask = null;
            }
        }

        class MyTask extends TimerTask {
            private Handler handler;

            public MyTask(Handler handler) {
                this.handler = handler;
            }

            @Override
            public void run() {
                handler.obtainMessage().sendToTarget();
            }

        }
    }

    public void setRefreshImage(int resId) {
        ImageView imageView = (ImageView) refreshingView;
        imageView.setBackgroundResource(resId);
    }

    public void setLoadMoreImage(int resId) {
        ImageView imageView = (ImageView) loadingView;
        imageView.setBackgroundResource(resId);
    }

    public void closePullToRefreshLayoutHandler() {
        if (myTimer != null) {
            myTimer.destoryCancel();
            myTimer = null;
        }
        updateHandler = null;
    }
}
